import type { ProColumns } from '@ant-design/pro-components';
import {
  EditableProTable,
} from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import LlmSelect from './LlmSelect';

interface DataSourceType {
  id: React.Key;
  label?: string;
  value?: string;
};

export interface DataSourceKeys {
  dataSource: DataSourceType[];
  editableKeys: React.Key[];
}

interface Props {
  value: DataSourceKeys;
  onChange: (value: DataSourceKeys) => void;
}

export default (props: Props) => {
  const { value, onChange } = props;
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([]);

  useEffect(() => {
    if (value?.dataSource) {
      setDataSource(value?.dataSource)
      setEditableRowKeys(value?.editableKeys)
    }
  }, [])

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '变量名',
      dataIndex: 'label',
      width: 170,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '变量名是必填项',
          },
          {
            pattern: /^[a-zA-Z_$][a-zA-Z0-9_$]*$/,
            message: '变量名只能以字母、下划线或 $ 开头，后续可以包含字母、数字、下划线或 $',
          }
        ],
      },
    },
    {
      title: '设置变量',
      dataIndex: 'value',
      width: 170,
      render: (text) => <span>{text}</span>,
      renderFormItem: () => <LlmSelect style={{ width: 100 }} />,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '变量名是必填项',
          }
        ],
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: () => {
        return null;
      }
    },
  ];

  return (
    <EditableProTable<DataSourceType>
      columns={columns}
      rowKey="id"
      value={dataSource}
      onChange={setDataSource}
      recordCreatorProps={{
        newRecordType: 'dataSource',
        record: () => ({
          id: Date.now(),
        }),
      }}
      editable={{
        type: 'multiple',
        editableKeys,
        actionRender: (row, config, defaultDoms) => {
          return [defaultDoms.delete];
        },
        onValuesChange: (record, recordList) => {
          onChange({
            dataSource: recordList,
            editableKeys,
          })

          setDataSource(recordList);
        },
        onChange: setEditableRowKeys,
      }}
    />
  );
};